package com.css.fxfzypg.modules.baseData.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;
import com.alibaba.fastjson.JSONObject;
import com.css.fxfzypg.base.attachment.service.AttachmentInfoService;
import com.css.fxfzypg.base.response.RestResponse;
import com.css.fxfzypg.common.utils.CheckObjFields;
import com.css.fxfzypg.common.utils.UpdateUtil;
import com.css.fxfzypg.constants.YNEnum;
import com.css.fxfzypg.modules.baseData.queryParams.EarthquakeDisasterQueryParams;
import com.css.fxfzypg.modules.baseData.repository.EarthquakeDisasterRepository;
import com.css.fxfzypg.modules.baseData.entity.EarthquakeDisasterEntity;
import com.css.fxfzypg.modules.baseData.service.EarthquakeDisasterService;
import com.css.fxfzypg.modules.baseData.vo.EarthquakeDisasterVO;
import com.css.fxfzypg.util.*;
import com.css.fxfzypg.web.PlatformSessionContext;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author y1fan
 * @create 2022-08-17 17:11
 */
@Service
@Slf4j
public class EarthquakeDisasterServiceImpl implements EarthquakeDisasterService {


    @Resource
    private EarthquakeDisasterRepository earthquakeDisasterRepository;
    @Resource
    AttachmentInfoService attachmentInfoService;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean saveEarthquakeDisaster(EarthquakeDisasterEntity earthquakeDisasterEntity) {
        earthquakeDisasterEntity.setDedCreateUser(PlatformSessionContext.getUserID());
        earthquakeDisasterEntity.setDedCreatetime(PlatformDateUtils.getCurrentTimestamp());
        earthquakeDisasterEntity.setDedIsdelete(YNEnum.N.toString());
        earthquakeDisasterEntity.setDedId(UUIDGenerator.getUUID());

        /*String date = sdf.format (sdf.parse (data));
        Date parse = sdf.parse(earthquakeDisasterEntity.getDedTime()*/
        Date parse = null;
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String format = sdf.format(earthquakeDisasterEntity.getDedTime());
            parse = sdf.parse(format);
        } catch (ParseException e) {
            e.printStackTrace();
        }
        earthquakeDisasterEntity.setDedHour(parse);
        return earthquakeDisasterRepository.saveEarthquakeDisaster(earthquakeDisasterEntity);
    }

    @Override
    public EarthquakeDisasterVO getEarthquakeDisasterById(String dataEarthquakeDisasterId) {
        EarthquakeDisasterEntity earthquakeDisaster = earthquakeDisasterRepository.getEarthquakeDisasterById(dataEarthquakeDisasterId);
        EarthquakeDisasterVO earthquakeDisasterVO=new EarthquakeDisasterVO();
        UpdateUtil.copyNullProperties(earthquakeDisaster, earthquakeDisasterVO);
        if (PlatformObjectUtils.isNotEmpty(earthquakeDisaster.getEnclosure())){
            earthquakeDisasterVO.setEnclosure(attachmentInfoService.queryFile(earthquakeDisaster.getEnclosure()));
        }
        if (PlatformObjectUtils.isNotEmpty(earthquakeDisaster.getTypicalEarthquakeDamagePicture())){
            earthquakeDisasterVO.setTypicalEarthquakeDamagePicture(attachmentInfoService.queryFile(earthquakeDisaster.getTypicalEarthquakeDamagePicture()));
        }
        if (PlatformObjectUtils.isNotEmpty(earthquakeDisaster.getIsoseismalLineAndIntensityPicture())){
            earthquakeDisasterVO.setIsoseismalLineAndIntensityPicture(attachmentInfoService.queryFile(earthquakeDisaster.getIsoseismalLineAndIntensityPicture()));
        }

        return earthquakeDisasterVO;
    }

    @Override
    public Map<String,Object> getAllEarthquakeDisasterByParams(EarthquakeDisasterQueryParams queryParams) {
        return earthquakeDisasterRepository.getAllEarthquakeDisasterByParams(queryParams);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateEarthquakeDisaster(EarthquakeDisasterEntity earthquakeDisasterEntity) {
        earthquakeDisasterEntity.setDedUpdateUser(PlatformSessionContext.getUserID());
        earthquakeDisasterEntity.setDedUpdatetime(PlatformDateUtils.getCurrentTimestamp());
        return earthquakeDisasterRepository.updateEarthquakeDisaster(earthquakeDisasterEntity);
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean deleteEarthquakeDisaster(List<String> ids) {
        return earthquakeDisasterRepository.deleteEarthquakeDisaster(ids);
    }

    @Override
    public void exportExcel(HttpServletResponse response, EarthquakeDisasterQueryParams queryParams) {
        List<EarthquakeDisasterVO> list = earthquakeDisasterRepository.findFormDataList(queryParams);
        if (list == null || list.size() <= 0) {
            throw new RuntimeException("数据为空,无法导出！");
        }
        try {
            EasyPoiExcelUtil.exportExcel(list, "历史地震灾害数据统计", "历史地震灾害数据", EarthquakeDisasterVO.class, "历史地震灾害数据", response);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    @Override
    @Transactional
    public RestResponse importExcel(MultipartFile file) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setTitleRows(0);
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<EarthquakeDisasterVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), EarthquakeDisasterVO.class, params);

            List<EarthquakeDisasterVO> list = result.getList();
            if(PlatformObjectUtils.isNotEmpty(list)){
                for (EarthquakeDisasterVO item:list){
                    EarthquakeDisasterEntity earthquakeDisaster=new EarthquakeDisasterEntity();
                    BeanUtils.copyProperties(item,earthquakeDisaster);
                    earthquakeDisaster.setDedCreateUser(PlatformSessionContext.getUserID());
                    earthquakeDisaster.setDedCreatetime(new Date());
                    earthquakeDisaster.setDedId(UUIDGenerator.getUUID());
                    earthquakeDisaster.setDedIsdelete(YNEnum.N.toString());

                    this.saveEarthquakeDisaster(earthquakeDisaster);
                }
                returnMsg.append("成功导入" + (result.getList().size()) + "条<br/>");
            }
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<EarthquakeDisasterVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    EarthquakeDisasterVO earthquakeDisasterVO = iterator.next();
                    EarthquakeDisasterEntity earthquakeDisaster=new EarthquakeDisasterEntity();
                    BeanUtils.copyProperties(earthquakeDisasterVO, earthquakeDisaster);
                    if (CheckObjFields.isAllFieldNull(earthquakeDisaster)){
                        continue;
                    }
                    returnMsg.append("第" + earthquakeDisasterVO.getRowNum() + "行 " + earthquakeDisasterVO.getErrorMsg() + "<br/>");
                }
            }
            return RestResponse.succeed(returnMsg.toString());
        } catch (Exception e) {
            log.error(e.getMessage(), e);
            return RestResponse.fail("导入失败，请检查数据正确性");
        }
    }

    @Override
    public Integer countByCounty(String name) {
        return earthquakeDisasterRepository.countByCounty(name);
    }

    @Override
    public Integer countByCity(String name) {
        return earthquakeDisasterRepository.countByCity(name);
    }

    @Override
    public Integer countByProvince(String name) {
        return earthquakeDisasterRepository.countByProvince(name);
    }

}
